# coding=utf-8
import sys
from datetime import datetime

import tornado.escape
import tornado.web
from tornado import ioloop
from tornado.httpserver import HTTPServer

from apis import auth_api, wx_api
from auth.utils import to_int

urls = [
    (r'/authapi/login', auth_api.LoginHandler),
    (r'/authapi/login2', auth_api.Login2Handler),
    (r'/authapi/login/wx', auth_api.LoginWithWxOpenIdHandler),
    (r'/authapi/login/wx/mini', wx_api.LoginWxMiniHandler),  # 微信小程序登陆
    (r'/authapi/token', auth_api.AuthValadeHandler),
    (r'/authapi/user/get', auth_api.UserGetHandler),
    (r'/authapi/user/update', auth_api.UserInfoUpdateHandler),
    (r'/authapi/user/detail', auth_api.UserInfoGetHandler),
    (r'/authapi/user/create', auth_api.UserCreateHandler),
    (r'/authapi/user/empty', auth_api.EmptyUserCreateHandler),  # 只是纯粹创建一个账号
    (r'/authapi/register', auth_api.RegisterHandler),  # 注册用户
    (r'/authapi/resetpwd', auth_api.ResetPwdHandler),  # 重置密码
    (r'/authapi/bind', auth_api.PhoneBindHandler),  # 绑定手机号码
    (r'/authapi/phone/change', auth_api.PhoneChangeHandler),  # 变更手机号码
    (r'/authapi/union/change', auth_api.UnionChangeHandler),  # 变更所在工会
    (r'.*', auth_api.OtherHandler)
]


def main(port):
    app = tornado.web.Application(urls, debug=False, gzip=True)
    # 启动服务器
    server = HTTPServer(app)  # 100Mb
    server.listen(port)
    print('运行在端口 : ' + str(port))
    ioloop.IOLoop.instance().start()


def get_cmd_params(argv_ls):
    dic = {}
    try:
        if not argv_ls: return dic

        for v in argv_ls:
            if r'=' not in v: continue
            res = v.split('=')
            dic[res[0].strip(' ')] = res[1].strip(' ')
        return dic
    except:
        return dic


if __name__ == '__main__':
    try:
        params = get_cmd_params(sys.argv)
        port = to_int(params.get('-port'))

        print(datetime.now())
        if not port:
            print('[失败]请指定端口')
        else:
            main(port)
    except Exception as e:
        print('启动服务', e)
